<?php

namespace app\user\controller\mall\order;

use app\user\controller\mall\Base;
use think\Db;
use app\common\model\mall\oper\Msgtpl;
use addons\mall\library\Service;
use think\Hook;

/**
 * 退单
 *
 * @icon fa fa-circle-o
 */
class Refund extends Base
{
    
    /**
     * Refund模型对象
     * @var \app\common\model\mall\order\Refund
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\mall\order\Refund;
        $this->view->assign("refundresonList", $this->model->getRefundresonList());
        $this->view->assign("refundstatusList", $this->model->getRefundstatusList());
    }

    public function index() {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()){
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')){
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model->alias("c")
                ->join("__MALL_ORDER_ORDER__ o", "c.order_id=o.id", "LEFT")
                ->field("c.*,o.orderNo")
                ->where("o.shop_id", cookie('shop_id'))
                ->where($where)
                ->count();

            $list = $this->model->alias("c")
                ->join("__MALL_ORDER_ORDER__ o", "c.order_id=o.id", "LEFT")
                ->field("c.*,o.orderNo")
                ->where("o.shop_id", cookie('shop_id'))
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 商家处理是否同意退款
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->alias('orf')
            ->join('__MALL_ORDER_ORDER__ o','orf.order_id=o.id', "RIGHT")
            ->where('orf.id',$ids)
            ->field('o.id order_id,orderNo,goodsMoney,deliverMoney,useScore,scoreMoney,totalMoney,realTotalMoney,orf.backMoney,orf.*')
            ->find();
        if (!$row) $this->error(__('No Results were found'));
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace("\\model\\", "\\validate\\", get_class($this->model)));
                        $validate = $this->modelSceneValidate ? $name . '.edit' : $name;
                        $result = $this->validate($params,$validate);
                        if(true !== $result){
                            // 验证失败 输出错误信息
                            $this->error($result);
                        }
                    }
                    $result = $row->allowField(true)->isUpdate(true)->save($params);
                    if ($result !== false) {
                        $order = Db::name('mall_order_order')->where('id',$row->order_id)->field('user_id,orderNo,id order_id,useScore')->find();
                        $content = $this->model->getRefundresonList()[$row["refundReson"]];
                        //如果是不同意退款要给用户发信息
                        $to = \app\common\model\User::where("id",$order['user_id'])
                            ->field("mobile,email")->find();
                        if((int)$params['refundStatus']==-1){
                            $find = ['${ORDER_NO}','${REASON}'];
                            $replace = [$order['orderNo'],$content];
                            $tplcontent = Msgtpl::getMsgByTpl('ORDER_REFUND_FAIL', $find, $replace);
                            if ($content != '') {
                                Service::smsAdminNotice($tplcontent,'orderrefund');
                                $template_id = 1;
Hook::listen('vbot_send_msg', $template_id, [
                                    'content'         => $tplcontent,
                                    'at_mobiles'     => $to['mobile'],
                                    'is_atall'       => 0,
                                ]);
                            }
                        }
                        else{
                            $find = ['${ORDER_NO}'];
                            $replace = [$order['orderNo']];
                            $content = Msgtpl::getMsgByTpl('PHONE_ADMIN_REFUND_ORDER', $find, $replace);
                            if ($content != '') {
                                Service::smsAdminNotice($content,'ordercomplain');
                                $template_id = 1;
Hook::listen('vbot_send_msg', $template_id, [
                                    'content'         => $content,
                                    'at_mobiles'     => $to['mobile'],
                                    'is_atall'       => 0,
                                ]);
                            }
                        }

                        Db::commit();
                        $this->success();
                    }else{
                        Db::rollback();
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign("row",$row);
        return $this->view->fetch();
    }


}
